package com.iot.iotplus.mqtt;

import lombok.Getter;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.UUID;

@Component
public class AcceptClient {
    @Autowired
    private MqttEntity mqttEntity;
    @Autowired
    private AcceptCallBack acceptCallBack;

    @Getter
    private static MqttClient client;

    private void setClient(MqttClient client) {
        AcceptClient.client = client;
    }

    /**
     * 连接mqtt服务器
     * @param username
     */
    public void connect(String username) {
        String clientId = UUID.randomUUID().toString().replace("-", "");
        MqttClient client = null;
        try {
            client = new MqttClient(mqttEntity.getHostUrl(), clientId, new MemoryPersistence());
            MqttConnectOptions options = new MqttConnectOptions();
            options.setUserName(username);
            options.setPassword(username.toCharArray());
            options.setAutomaticReconnect(true);
            client.setCallback(acceptCallBack);
            client.connect(options);
            setClient(client);
        } catch (MqttException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 重新连接mqtt服务器
     */
    public static void reconnect() {
        try {
            getClient().reconnect();
        } catch (MqttException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 订阅主题
     * @param topic
     */
    public void subscribe(String topic) {
        try {
            getClient().subscribe(topic);
        } catch (MqttException e) {
            throw new RuntimeException(e);
        }
    }

    //取消继续订阅主题
    public void unsubscribe(String topic) {
        try {
            getClient().unsubscribe(topic);
        } catch (MqttException e) {
            throw new RuntimeException(e);
        }
    }

    //主动关闭连接
    public void close() {
        try {
            getClient().disconnect();
        } catch (MqttException e) {
            throw new RuntimeException(e);
        }
    }

}
